<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@include file="/WEB-INF/views/init.jsp"%>
<%--@elvariable id="locationFromId" type="java.lang.Long"--%>
<%--@elvariable id="locationToId" type="java.lang.Long"--%>
<%--@elvariable id="locationFromName" type="java.lang.String"--%>
<%--@elvariable id="locationToName" type="java.lang.String"--%>

<script type="text/javascript">

    $(document).ready(function(){

        var sourceLocation = function( request, response, countryId) {
            $.ajax({
                url: "<spring:url value="/calculator/locations"/>",
                dataType: "json",
                async: false,
                type: "POST",
                data: {
                    locationName: request.term,
                    countryId: countryId
                },
                success: function(data){
                    response(data);
                }
            });
        }

        var sourcelocationFrom = function(request, response){
            var countryId = $("input[name=countryFromId]:checked").val();
            sourceLocation(request, response, countryId);
        }

        var sourcelocationTo = function(request, response){
            var countryId = $("input[name=countryToId]:checked").val();
            sourceLocation(request, response, countryId);
        }

        $.widget( "custom.catcomplete", $.ui.autocomplete, {
            _renderMenu: function( ul, items ) {
                var that = this,
                        currentCategory = "";
                $.each( items, function( index, item ) {
                    if ( item.category != currentCategory ) {
                        ul.append( "<li class='ui-autocomplete-category'>" + item.category + "</li>" );
                        currentCategory = item.category;
                    }
                    that._renderItemData( ul, item );
                });
            }
        });

        $( "#countryFromId" ).buttonset();
        $( "input[name=countryFromId]" ).change(function(){
            $( "#locationFrom" ).removeAttr("disabled");
        });
        $( "#countryToId" ).buttonset();
        $( "input[name=countryToId]" ).change(function(){
            $( "#locationTo" ).removeAttr("disabled");
        });


        $("#locationFrom").catcomplete({
            source: sourcelocationFrom
        });

        $("#locationTo").catcomplete({
            source: sourcelocationTo
        });

        $("input[type=button],button").button();

        <c:if test="${!empty locationFromId &&  !empty locationToId}">
        var ajaxDataRenderer = function(url, plot, options) {
            var ret = null;
            $.ajax({
                url: url,
                type: "post",
                async: false,
                dataType:"json",
                success: function(data) {
                    ret = data;
                }
            });
            return ret;

        };

        <c:url var="url" value="/pricing/cargo-price/chart/json">
        <c:param name="locationFromId" value="${locationFromId}"/>
        <c:param name="locationToId" value="${locationToId}"/>
        </c:url>

        var jsonUrl = "${url}";

        var plot = $.jqplot('chart', jsonUrl,{
            title: "Маршрут: <c:out value="${locationFromName}"/>-<c:out value="${locationToName}"/>",
            dataRenderer: ajaxDataRenderer,
            dataRendererOptions: {
                unusedOptionalUrl: jsonUrl
            },
            highlighter: {
                show: true,
                sizeAdjust: 7.5
            },
            cursor: {
                show: true,
                tooltipLocation:'sw'
            }
        });

        <spring:url var="generalCargoPricingGridUrl" value="/pricing/cargo-price/table/json">
            <spring:param name="locationFromId" value="${locationFromId}"/>
            <spring:param name="locationToId" value="${locationToId}"/>
            <spring:param name="cargoType" value="GENERAL"/>
        </spring:url>

        <spring:url var="separateCargoPricingGridUrl" value="/pricing/cargo-price/table/json">
        <spring:param name="locationFromId" value="${locationFromId}"/>
        <spring:param name="locationToId" value="${locationToId}"/>
        <spring:param name="cargoType" value="SEPARATE"/>
        </spring:url>

        jQuery("#generalCargoPricingGrid").jqGrid({
            url:"${generalCargoPricingGridUrl}",
            datatype: "json",
            colNames:['ID','Наименование', 'Объем(кубы)', 'Вес(т)','Длина(м)','Процент','Цена(руб)'],
            colModel:[
                {name:'id',index:'id', width:70, align:"left", sortable:false, editable:false},
                {name:'name',index:'name', width:80, align:"left", sortable:false, editable:false},
                {name:'cbm',index:'cbm', width:70, align:"left", sortable:false, editable:false},
                {name:'weight',index:'weight', width:70, align:"left", sortable:false, editable:false},
                {name:'length',index:'length', width:70, align:"left", sortable:false, editable:false},
                {name:'percent',index:'percent', width:70, align:"left", sortable:false, editable:false},
                {name:'price',index:'price', width:80, align:"left", sortable:false, editable:false}
            ],
            rowNum:10,
            rowList:[10,20,30],
//            pager: "#generalCargoPricingGridPager",
            sortname: "id",
            viewrecords: true,
            sortorder: "desc",
            editurl: "<spring:url value="/table/json"/>",
            caption: "Ценообразование сборных грузов",
            cellEdit: true,
            cellsubmit : "remote",
            cellurl : "<spring:url value="/table/json"/>",
            loadComplete: function(){
//                alert("load complete");
            },
            gridComplete: function(){
//                alert("grid complete");
            },
            afterInsertRow: function(){
//                alert("after insert row");
            },
            afterEditCell: function(){
//                alert("after edit cell");
            },
            afterRestoreCell: function(){
//                alert("after restore cell");
            },
            afterSaveCell: function(){
//                alert("after save cell");
            }
        });
        /*jQuery("#generalCargoPricingGrid").jqGrid('navGrid',"#pager",{edit:false,add:false,del:false});
         jQuery("#generalCargoPricingGrid").jqGrid('inlineNav',"#pager");*/

        jQuery("#separateCargoPricingGrid").jqGrid({
            url:"${separateCargoPricingGridUrl}",
            datatype: "json",
            colNames:['ID','Наименование', 'Объем(кубы)', 'Вес(т)','Длина(м)','Процент','Цена(руб)'],
            colModel:[
                {name:'id',index:'id', width:70, align:"left", sortable:false, editable:false},
                {name:'name',index:'name', width:80, align:"left", sortable:false, editable:false},
                {name:'cbm',index:'cbm', width:70, align:"left", sortable:false, editable:false},
                {name:'weight',index:'weight', width:70, align:"left", sortable:false, editable:false},
                {name:'length',index:'length', width:70, align:"left", sortable:false, editable:false},
                {name:'percent',index:'percent', width:70, align:"left", sortable:false, editable:false},
                {name:'price',index:'price', width:80, align:"left", sortable:false, editable:false}
            ],
            rowNum:10,
            rowList:[10,20,30],
//            pager: "#separateCargoPricingGridPager",
            sortname: "id",
            viewrecords: true,
            sortorder: "desc",
            editurl: "<spring:url value="/table/json"/>",
            caption: "Ценообразование отдельных грузов",
            cellEdit: true,
            cellsubmit : "remote",
            cellurl : "<spring:url value="/table/json"/>",
            loadComplete: function(){
//                alert("load complete");
            },
            gridComplete: function(){
//                alert("grid complete");
            },
            afterInsertRow: function(){
//                alert("after insert row");
            },
            afterEditCell: function(){
//                alert("after edit cell");
            },
            afterRestoreCell: function(){
//                alert("after restore cell");
            },
            afterSaveCell: function(){
//                alert("after save cell");
            }
        });
        /*jQuery("#separateCargoPricingGrid").jqGrid('navGrid',"#pager",{edit:false,add:false,del:false});
         jQuery("#separateCargoPricingGrid").jqGrid('inlineNav',"#pager");*/
        </c:if>


    });
</script>

<%--<a href="<spring:url value="/"/>">&#8592; На Главную</a>--%>
<h1>Параметры ценообразования</h1>

<c:url var="action" value="/pricing"/>
<form:form modelAttribute="pricingForm" method="POST" action="${action}">
    <div class="location">
        <h4>Пункт отправки</h4>
        <div id="countryFromId">
            <c:forEach items="${countries}" var="country" varStatus="status">
                <form:radiobutton id="countryFromId${country.id}" path="countryFromId" value="${country.id}"/>
                <label for="countryFromId${country.id}"><c:out value="${country.name}"/></label>
            </c:forEach>
        </div>
        <form:input id="locationFrom" disabled="${empty pricingForm.countryFromId}" path="locationFrom" type="text" placeholder="Выберите пункт отправки"/>
        <div class="error">${locationFromError}</div>
    </div>
    <div class="location">
        <h4>Пункт назначения</h4>
        <div id="countryToId">
            <c:forEach items="${countries}" var="country">
                <form:radiobutton id="countryToId${country.id}" path="countryToId" value="${country.id}"/>
                <label for="countryToId${country.id}"><c:out value="${country.name}"/></label>
            </c:forEach>
        </div>
        <form:input id="locationTo" disabled="${empty pricingForm.countryToId}" path="locationTo" placeholder="Выберите пункт назначения"/>
        <div class="error">${locationToError}</div>
    </div>
    <div style="clear: both;"/>
    <form:button>Показать</form:button>
    <span class="error"><c:out value="${commonError}"/></span>
</form:form>

<div id="chart" style="height:400px;width:600px; "></div>

<div style="margin-top: 20px;">
    <table id="generalCargoPricingGrid"></table>
    <div id="generalCargoPricingGridPager"></div>
</div>

<div style="margin-top: 20px;">
    <table id="separateCargoPricingGrid"></table>
    <div id="separateCargoPricingGridPager"></div>
</div>